package com.atguigu.interview.study.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData {
    public int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public void increment() {
        lock.lock();
        try {
            while (number != 0) {
                //1、等待不能生产
                condition.await();
            }
            // 2、干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t" + number);
            // 通知维修
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                //1、等待不能生产
                condition.await();
            }
            // 2、干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t" + number);
            // 通知维修
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


/**
 * @author gcq
 * @Create 2020-11-24
 * 题目：一个初始值为零的变量，两个线程对其交替操作，一个加1一个减1来 5轮
 *
 * 1、线程 操作(方法) 资源类
 * 2、判断 干活 同志
 * 3、防止虚假唤醒机制
 */
public class ProdConsumer_TradtionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for(int i = 1; i <= 5; i++) {
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();

        new Thread(() -> {
            for(int i = 1; i <= 5; i++) {
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"t2").start();


        new Thread(() -> {
            for(int i = 1; i <= 5; i++) {
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"t3").start();

        new Thread(() -> {
            for(int i = 1; i <= 5; i++) {
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"t4").start();
    }
}